<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

if (!function_exists('StrMD5')) {
    /**
     * 字符串加密处理
     * @param unknown $str  字符串
     * @return string  加密后的字符串
     */
    function StrMD5($str)
    {
        return substr(md5($str . "LycPhp!9*61)0^"), 5, 20);
    }
}
if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {   
        
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = config('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }else{
            $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
            $url = $protocol.$_SERVER['HTTP_HOST']."/". $url;
        }
        return $url;
    }
}

if (!function_exists('get_distance')) {
 /**
     * 根据起点坐标和终点坐标测距离
     * @param  [array]   $from 	[起点坐标(经纬度),例如:array(118.012951,36.810024)]
     * @param  [array]   $to 	[终点坐标(经纬度)]
     * @param  [bool]    $km        是否以公里为单位 false:米 true:公里(千米)
     * @param  [int]     $decimal   精度 保留小数位数
     * @return [string]  距离数值
     */
    function get_distance($from,$to,$km=true,$decimal=2){

        $from = [
            0 =>  trim($from[0]),
            1 =>  trim($from[1]),
        ];
        
        $to = [
            0 =>  trim($to[0]),
            1 =>  trim($to[1]),
        ];
        sort($from);
        sort($to);
        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $distance = $EARTH_RADIUS*2*asin(sqrt(pow(sin( ($from[0]*pi()/180-$to[0]*pi()/180)/2),2)+cos($from[0]*pi()/180)*cos($to[0]*pi()/180)* pow(sin( ($from[1]*pi()/180-$to[1]*pi()/180)/2),2)))*1000;
        if($km){
            $distance = $distance / 1000;
        }
        return round($distance, $decimal);
    }
}
if (!function_exists('encryption_name')) {
     /**
     * 加密昵称
     */
    function encryption_name($user_name){
        $strlen = mb_strlen($user_name, 'utf-8');
        if($strlen<2){
            return $user_name."*";
        }else{
            $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
            $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
            return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
        }
    }
}
if (!function_exists('worker_url')) {
    /**
    * 发送
    *msg = 内容
    *type = 发送消息类型
    *order_type = 消息类型
    *port 端口
    */
   function worker_url($msg,$type,$uid,$order_type,$port){
        $arr = [
            'Worker' => 56781, #商家端外卖订单
            'Rider' => 56782, #骑手端外卖订单
            'User' => 56783,#用户端外卖订单
            'UserBuy' => 56784, #用户端帮我买
            'UserDriving' => 56785, #用户端代驾
            'UserRunning' => 56786,  #用户端跑腿
            'RiderBuy' => 56787,  #骑手端帮我买
            'RiderDriving' => 56788, #骑手端-代驾
            'RiderRunning' => 56789, #骑手端跑腿
            'StoreMp3' => 56790, #商家推送音频
            'RiderMp3' => 56791, #骑手推送音频
        ];
        $client = stream_socket_client("tcp://o2onew.ccfqkj.com:{$arr[$port]}", $errno, $errmsg, 1);
        // 推送的数据，包含用户，表示是给这个用户推送
        $data = array('uid'=>$uid, 'message'=>json_encode([
            'data' => $msg,
            'type' => $order_type,
            'uid' => $uid,
        ]),'type'=>$type);
        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($data)."\n");
        // 读取推送结果
        return fread($client, 8192);
   }
}

// 
if (!function_exists('wconfig')) {
    /**
    * 发送
    *msg = 内容
    *type = 类型
    */
   function wconfig($key){
        return db('config')->where('key',$key)->value('value');
    }
}
if (!function_exists('array_get')) {

    function array_get($array, $key, $default = null)
    {
        return isset($array[$key]) ? $array[$key] : $default;
    }
}
if (!function_exists('gaode_address')) {

    function gaode_address($longitude,$latitude)
    {   
      
        $key="3e2e3064ef448efee5f4664dc6cfb8b6";
        //高德地图的api接口,根据详细地址获取经纬度
        $regeo_url="https://restapi.amap.com/v3/geocode/regeo?output=josn&location=$longitude,$latitude&key=$key&radius=1000&extensions=all";
    
        $data_location=file_get_contents($regeo_url);
        $result_local=json_decode($data_location,true);
        $local_status=$result_local['status'];
        $local_infocode=$result_local['infocode'];
       
        if($local_status==1 && $local_infocode == 10000 ){
            return [
                'status'=>1,
                'data'=>[
                    'formatted_address' => $result_local['regeocode']['formatted_address'],
                    'addressComponent' => [
                        'province' => empty($result_local['regeocode']['addressComponent']['province']) ? '' : $result_local['regeocode']['addressComponent']['province'],
                        'city' => empty($result_local['regeocode']['addressComponent']['city']) ? '' : $result_local['regeocode']['addressComponent']['city'],
                        'area' => empty($result_local['regeocode']['addressComponent']['district']) ? '' : $result_local['regeocode']['addressComponent']['district'],
                    ]
                    
                ]
            ];
        }else{
            return ['status'=>0, 'msg'=>'地图API调用失败'];
        }

    }
}
if (!function_exists('aconfig')) {
    /**
    * 发送
    *msg = 内容
    *type = 类型
    */
   function aconfig($key,$agent_id){
        return db('agent_config')->where('agent_id',$agent_id)->value($key);
    }
}


